#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : HighlightText.py
# Purpose  : window to set Syntax Highlighter
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-09-17 00:58
# ==============================================================================
import sys

from PyQt5.QtCore import pyqtSignal, Qt, QSize
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QHBoxLayout, QGridLayout, QDialogButtonBox,\
    QListWidget, QCheckBox, QLineEdit, QColorDialog, QListWidgetItem

from conf.settings import Setting


class TextHighlighter(QWidget):
    re_highlighter = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super(TextHighlighter, self).__init__(*args, **kwargs)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.9)
        self.resize(500, 700)
        self.move(int((QApplication.desktop().screen().width() - self.width()) / 2),
                  int((QApplication.desktop().screen().height() - self.height()) / 3))
        self._init_ui()

    def _init_ui(self):
        self.item_list = WidgetList()
        self.btn_add = QPushButton('+')
        self.btn_add.clicked.connect(self.item_list.add_item)
        self.btn_sub = QPushButton('-')
        self.btn_sub.clicked.connect(self.item_list.del_item)
        self.btn_cancel = QPushButton('Cancel')
        self.btn_cancel.clicked.connect(self.close)
        self.btn_ok = QPushButton('OK')
        self.btn_ok.clicked.connect(self.set_cur_widget_highlighter)
        self.btn_ok.clicked.connect(self.close)
        self.btn_box = QDialogButtonBox()
        self.btn_box.addButton(self.btn_ok, QDialogButtonBox.AcceptRole)
        self.btn_box.addButton(self.btn_cancel, QDialogButtonBox.RejectRole)

        lay = QGridLayout(self)
        lay.addWidget(self.item_list, 1, 1, 1, 4)
        lay.addWidget(self.btn_add, 2, 1, 1, 1)
        lay.addWidget(self.btn_sub, 2, 2, 1, 1)
        lay.addWidget(self.btn_box, 2, 3, 1, 2)

    def set_cur_widget_highlighter(self):
        # for i in self.item_list
        Setting().setValue('highlighter', self.item_list.get_data())
        self.re_highlighter.emit()


class WidgetList(QListWidget):
    def __init__(self, *args, **kwargs):
        super(WidgetList, self).__init__(*args, **kwargs)
        self._init_list()

    def add_item(self, item_=None):
        item = QListWidgetItem()
        item.setSizeHint(QSize(-1, 40))
        item_widget = item_ or Item()
        self.addItem(item)
        self.setItemWidget(item, item_widget)

    def del_item(self):
        self.removeItemWidget(self.currentItem())
        self.takeItem(self.currentRow())

    def get_data(self):
        v = []
        for i in range(self.count()):
            value_ = self.itemWidget(self.item(i)).value()
            v.append(value_) if value_ else ''
        else:
            return v

    def _init_list(self):
        v = Setting().value('highlighter', None)
        if v:
            for t, f, b in v:
                self.add_item(Item(t, f, b))
        else:
            pass


class Item(QWidget):
    def __init__(self, text__='', f_color_=QColor('#000000'), b_color_=QColor('#FFFFFF'), *args, **kwargs):
        super(Item, self).__init__(*args, **kwargs)
        self.f_color_ = f_color_
        self.b_color_ = b_color_
        self.text__ = text__
        self._init_ui()

    def _init_ui(self):
        self.valid = QCheckBox()
        self.valid.setChecked(True)
        self.valid.clicked.connect(self.set_if_valid)
        self.text_ = QLineEdit(self.text__)
        pal = self.text_.palette()
        pal.setColor(QPalette.Text, self.f_color_)
        pal.setColor(QPalette.Base, self.b_color_)
        self.text_.setPalette(pal)
        self.text_.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.text_.setFixedHeight(20)
        self.f_color = QPushButton('a')
        self.f_color.setToolTip(f"Foreground color")
        self.f_color.clicked.connect(self.get_f_color)
        self.f_color.setAutoFillBackground(True)
        self.f_color.setStyleSheet(f"background: rgba{str(self.f_color_.getRgb())}")
        self.f_color.setFixedSize(40, 20)
        self.b_color = QPushButton('b')
        self.b_color.setToolTip(f"Background color")
        self.b_color.clicked.connect(self.get_b_color)
        self.b_color.setAutoFillBackground(True)
        self.b_color.setStyleSheet(f"background: rgba{str(self.b_color_.getRgb())}")
        self.b_color.setFixedSize(40, 20)
        lay = QHBoxLayout(self)
        lay.addWidget(self.valid)
        lay.addWidget(self.text_)
        lay.addSpacing(10)
        lay.addWidget(self.f_color)
        lay.addSpacing(10)
        lay.addWidget(self.b_color)

    def get_f_color(self):
        color = QColorDialog.getColor(Qt.green, self)
        if color.isValid():
            palette_ = self.text_.palette()
            palette_.setColor(QPalette.Text, color)
            self.text_.setPalette(palette_)
            self.f_color.setStyleSheet(f"background-color: rgba{str(color.getRgb())}")
            self.f_color_ = color

    def get_b_color(self):
        color = QColorDialog.getColor(Qt.green, self)
        if color.isValid():
            self.b_color.setPalette(QPalette(color))
            palette_ = self.text_.palette()
            palette_.setColor(QPalette.Base, color)
            self.text_.setPalette(palette_)
            self.b_color.setStyleSheet(f"background-color: rgba{str(color.getRgb())}")
            self.b_color_ = color

    def set_if_valid(self, v: bool):
        self.text_.setEnabled(v)
        self.f_color.setEnabled(v)
        self.b_color.setEnabled(v)

    def value(self):
        if self.valid.isChecked():
            return self.text_.text(), self.f_color_, self.b_color_
        else:
            return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    t = TextHighlighter()
    t.show()
    sys.exit(app.exec_())
